/**
 * Created by root on 2017-08-10. router-即信一览
 */
import React, { Component, PropTypes } from 'react';
import { Utility, GxIcon, GxSearchBar, Tabs, TaskList, Refresh, ApiInfo } from 'components';
import { connect } from 'react-redux';
import * as CommonActions from 'redux/modules/reduxCommon';
const styles = require('./scss/GmessageView.scss');

@connect(
  state => ({
    Title: state.Common.Title,                                          // 标题
    UrlParams: state.Common.UrlParams,                                  // URL参数
    TaskListInfo: state.Common.TaskListInfo,                            // 活动列表
    CurrentTIndex: state.Common.CurrentTIndex                           // 当前页面选中的tab
  }),
  { ...CommonActions })

export default class GmessageView extends Component {
  static propTypes = {
    Title: PropTypes.string,                                            // 标题
    UrlParams: PropTypes.object,                                        // url 参数
    TaskListInfo: PropTypes.object,                                     // 活动列表
    CurrentTIndex: PropTypes.object,                                    // 当前页面选中的tab
    onApiGet: PropTypes.func,                                           // Get请求
    onClearContent: PropTypes.func,                                     // clear content
    onSetContent: PropTypes.func,                                       // save content
  };

  constructor(props) {
    super(props);
    this.state = {
      RefreshComplete: true,
      NextDataComplete: true,
      __Index: 0,
      IsNoteData: false,                                                 // 判断有无数据
      TaskLists: [],                                                     // 处理之后的任务列表
      TIndex: 0,                                                         // tab选中
      ConditionInfo: {}
    };
    this.state.TabList = [
      { Title: '待处理的任务', Status: 0, onSelect: this.__HandlerSwitchTab.bind(this) },
      { Title: '根据创建时间排序', Status: 1, onSelect: this.__HandlerSwitchTab.bind(this) },
    ];
  }
  componentWillMount() {
    // this.__TaskListData();
    // setTimeout(() => {
    //   this.__InitData();
    // }, 0);
    const { onClearContent, CurrentTIndex } = this.props;
    const { TIndex } = CurrentTIndex || {};
    this.state.TIndex = TIndex || 0;
    onClearContent('TaskAssignCondition');
  }

  componentDidMount() {
    this.state.IsMount = true;
    // const { TaskListInfo } = this.props;
    // const { List } = TaskListInfo || {};
    // if (!Utility.isArray(List)) {
    //   this.__InitData({}, true);
    // }
    this.__InitConditionInfo();
    this.__InitData({}, true);
  }

  componentWillUnmount() {
    delete this.state.IsMount;
    const { onClearContent } = this.props;
    onClearContent('TaskAssignCondition');
  }

  __InitConditionInfo() {
    const { ConditionInfo } = this.state;
    ConditionInfo.up = Utility.$getInitPageTurning();
    ConditionInfo.up.action_type = 'up';
    ConditionInfo.up.pg_index = 1;
    ConditionInfo.down = Utility.$getInitPageTurning();
    ConditionInfo.down.action_type = 'down';
  }

  /**
   * 初始化页面数据
   * @returns 
   * @memberof GmessageView
   */
  __InitData(condition, isNextData) {
    const { onApiGet, TaskListInfo } = this.props;
    const { TIndex } = this.state;
    if (!Utility.isFunction(onApiGet)) {
      return;
    }
    const _statusParams = {};
    _statusParams.type = '@wo';
    _statusParams.list_type = 'deadline';
    _statusParams.action_type = 'down';
    _statusParams.status = ['START', 'RECEIVED'];

    const _createParams = {};
    _createParams.list_type = 'create';
    // _createParams.action_type = 'down';

    const __params = Object.assign(TIndex === 0 ? _statusParams : _createParams, Utility.$getInitPageTurning(), condition || {});
    const __self = this;
    const __ApiList = [];
    const { List } = TaskListInfo || {};
    if (document.body.scrollTop === 0 || !Utility.isArray(List) || !!isNextData) {
      __ApiList.push(onApiGet('TaskListInfo', ApiInfo.Task.TaskLists, { params: __params }));
    }
    if (!isNextData) {
      Utility.$loadingHide();
    } else {
      Utility.$loading();
    }
    Promise.all(__ApiList).then(() => {
      // __self.__TaskListYear();
      __self.__InitDataByResult();
      // __self.__TaskListData();
      __self.__JudgeIsExistData();
      __self.state.RefreshComplete = true;
      __self.state.NextDataComplete = true;
      __self.__UpdateRender();
      Utility.$loadingHide();
    }).catch((ex) => {
      __self.__JudgeIsExistData();
      __self.state.RefreshComplete = true;
      __self.state.NextDataComplete = true;
      __self.__UpdateRender();
      Utility.$loadingHide();
      console.log(ex);
    });
  }

  __InitDataByResult() {
    const { TaskListInfo } = this.props;
    const { Condition } = TaskListInfo || {};
    const { IsExistsNextData, action_type } = Condition || {};
    this.state.IsNextData = IsExistsNextData;
    const { ConditionInfo } = this.state;
    ConditionInfo[action_type] = Condition;
  }

  /**
   * 判断有无数据列表
   * 
   * @returns 
   * @memberof GmessageView
   */
  __JudgeIsExistData() {
    const { TaskListInfo } = this.props;
    if (TaskListInfo) {
      if (Utility.isArray(TaskListInfo.List)) {
        return;
      }
    }

    this.state.IsNotData = true;
  }

  /**
   * Tab切换
   * 
   * @param {any} item 
   * @param {any} index 
   * @memberof GmessageView
   */
  __HandlerSwitchTab(item, index) {
    const { onSetContent } = this.props;
    this.state.TIndex = index;
    this.state.RefreshComplete = false;
    this.__UpdateRender();
    this.__InitConditionInfo();
    this.__InitData({}, false);
    onSetContent('CurrentTIndex', { TIndex: this.state.TIndex });
  }

  /**
   * 上拉加载
   * @memberof GmessageView
   */
  __HandlerNextData() {
    const { TaskListInfo } = this.props;
    const { Condition } = TaskListInfo || {};
    const { ConditionInfo, TIndex } = this.state;
    const { down } = ConditionInfo;
    // const { IsExistsNextData } = down || Condition;
    const IsExistsNextData = TIndex === 0 ? down.IsExistsNextData : Condition.IsExistsNextData;
    if (!IsExistsNextData) {
      return;
    }
    this.state.NextDataComplete = false;
    this.__UpdateRender();

    this.__InitData(TIndex === 0 ? down : Condition, true);
  }

  /**
   * 下拉刷新
   * @memberof GmessageView
   */
  __HandlerRefreshData() {
    const { ConditionInfo, TIndex } = this.state;
    const { up } = ConditionInfo;
    const { IsExistsNextData } = up;
    if (IsExistsNextData === false) {
      return;
    }
    this.state.RefreshComplete = false;
    this.__UpdateRender();

    this.__InitData(TIndex === 0 ? up : {}, false);
  }

  /**
   * 更新渲染
   */
  __UpdateRender() {
    if (!!this.state.IsMount) {
      this.setState({ __CurrentTempDate: new Date().getTime() });
    }
  }

  /**
   * IsToPage 跳转到搜索页面
   * 
   * @memberof GmessageView
   */
  __HandlerClickTo(type) {
    const { UrlParams } = this.props;
    const { token } = UrlParams || {};
    let __token = '';
    if (token) {
      __token = token;
    }
    const { SearchPage } = Utility.constItem.UrlItem;
    if (SearchPage) {
      Utility.toPage(SearchPage, { type: type, token: __token });
    }
  }

  /**
   * 按照年划分
   * 分别找到每个年的数据 _Year: 2017, list: []
   * @returns 
   * @memberof GmessageView
   */
  __TaskListYear() {
    const { TaskListInfo } = this.props;
    const { TIndex } = this.state;
    const { List } = TaskListInfo || {};
    if (!Utility.isArray(List)) {
      return [];
    }
    const _info = {};
    const currentTime = new Date().getTime();
    for (let i = 0; i < List.length; i++) {
      const item = List[i];
      const _Time = new Date(TIndex === 0 ? (item.deadline ? item.deadline : currentTime) : item.createTime);
      const _Year = _Time.getFullYear();
      if (!_info[_Year]) {
        _info[_Year] = { _Year: _Year, list: [] };
      }
      _info[_Year].list.push(item);
    }
    const resultYear = Object.values(_info);
    if (!Utility.isArray(resultYear)) {
      return [];
    }
    const __data = resultYear.reverse();
    return __data;
  }

  /**
   * 按照每年-月树状结构处理数据
   * 
   * @returns 每个月对应的数据集合 
   * @memberof TaskList
   */
  __TaskListData(TaskLists) {
    const { TIndex } = this.state;
    // const { TaskListInfo } = this.props;
    // const { List } = TaskListInfo || {};
    // const TaskLists = List || [];
    // const TaskLists = this.__TaskListYear();
    if (!Utility.isArray(TaskLists)) {
      return null;
    }
    const monthOfYear = ['12月', '11月', '10月', '09月', '08月', '07月', '06月', '05月', '04月', '03月', '02月', '01月'];
    const __formatMonth = 'yyyy年MM月';
    // const __formatDay = 'yyyy年MM月dd日';
    const currentTime = new Date().getTime();
    const resultMonth = [];
    let result = [];
    for (let i = 0; i < monthOfYear.length; i++) {
      result = [];
      const item = monthOfYear[i];
      for (let j = 0; j < TaskLists.length; j++) {
        const row = TaskLists[j];
        const __createTimeMonth = Utility.$convertToDateByTimestamp(TIndex === 0 ? (row.deadline ? row.deadline : currentTime) : row.createTime, __formatMonth) + '';
        const month = __createTimeMonth.slice(-3);
        if (item === month) {
          result.push(row);
        }
        // break;
      }
      if (result.length !== 0) {
        resultMonth.push(result);
      }
    }
    return resultMonth;
    // if (Utility.isArray(resultMonth)) {
    //   return;
    // }
    // this.setState({ TaskLists: resultMonth });
  }

  /**
   * 遍历每年对应的列表HTMl
   * 
   * @memberof GmessageView
   */
  __MapYearHtml() {
    const data = this.__TaskListYear();
    if (!Utility.isArray(data)) {
      return null;
    }
    return data.map((year, index) => {
      const { list } = year;
      if (!Utility.isArray(list)) {
        return null;
      }
      const TaskLists = this.__TaskListData(list);
      return (
        <div className={styles.yearContainer} key={'_year_list' + index}>
          {this.__TaskListMapHtml(TaskLists)}
        </div>
      );
    });
  }

  /**
   * 遍历每年各个月份对应的任务列表
   * 
   * @param {any} styles 
   * @returns 
   * @memberof GmessageView
   */
  __TaskListMapHtml(TaskLists) {
    const { TIndex } = this.state;
    if (!Utility.isArray(TaskLists)) {
      return null;
    }
    const currentTime = new Date().getTime();
    return TaskLists.map((list, index) => {
      const listOne = list[0] || [];
      const { createTime, deadline } = listOne || {};
      // console.log(createTime);
      const _key = TIndex === 0 ? 'deadline_list_item' : 'create_time_list_item';
      return (
        <div className={styles.listItemCss} key={_key + index}>
          <TaskList TaskLists={list} TIndex={TIndex} createTime={TIndex === 0 ? (deadline ? deadline : currentTime) : createTime} />
        </div>
      );
    });
  }

  render() {
    const { RefreshComplete, NextDataComplete, TabList, TIndex, IsNextData } = this.state;

    return (
      <div className={styles.messageViewCss}>
        <div className={styles.searchContainer}>
          <div className={styles.screening} onClick={this.__HandlerClickTo.bind(this, 0)}>
            <div className={styles.screen}>筛选</div>
            <div>
              <GxIcon IconType="iconDown" />
            </div>
          </div>
          <div className={styles.search}>
            <GxSearchBar ref="searchBar" Title="搜索" IsToPage IsHideCancel onClick={this.__HandlerClickTo.bind(this, 1)} />
          </div>
        </div>
        <Tabs Items={TabList} SelectIndex={TIndex || 0} />
        <Refresh Percentage={20} MarginBottom={20} RefreshComplete={RefreshComplete} NextDataComplete={NextDataComplete}
          onNextData={this.__HandlerNextData.bind(this)}
          onRefresh={this.__HandlerRefreshData.bind(this)}>
          <div className={styles.container}>
            {this.__MapYearHtml()}
          </div>
        </Refresh>
        <div className={styles.last}>
          {
            IsNextData === false &&
            <span> 别扯了,我是有底线的。</span>
          }
        </div>
      </div>
    );
  }
}

